<template>
  <div>
    <el-input
      clearable
      v-model.trim="uploadImgUrl"
      size="mini"
      @change="changeInput"
    >
      <template slot="append">
        <i class="iconfont iconfolder-o"></i>
        <input type="file" class="file" ref="files" ass @change="getImages" />
      </template>
    </el-input>
    <img v-if="uploadImgUrl" class="uploadimg" :src="uploadImgUrl + token" alt="" />
  </div>
</template>
<script>
import request from "@/utils/request";
import { getToken } from '@/utils/auth';
export default {
  model: {
    prop: "value",
    event: "input",
  },
  props: {
    value: {
      type: "",
      default: "",
    },
  },
  data() {
    return {
      fileList: [],
      uploadImgUrl: "",
      token: `&Authorization=${getToken()}`
    };
  },
  mounted() {
    this.uploadImgUrl = this.value;
  },
  watch: {
    value(val) {
      this.uploadImgUrl = val;
    },
  },
  methods: {
    getImages(el) {
      var file = el.target.files[0];
      var type = file.type.split("/")[0];
      if (type === "image") {
        this.upload(file);
      } else {
        this.$message.warn("只能上传图片格式");
      }
    },
    // 上传
    upload(file) {
      var formdata = new FormData();
      formdata.append("file", file);
        // window.globalRequest("/api/fileuploadallfile", {
        request("/api/fileuploadallfile", {
          method: "POST",
          prefix: "/religion",
          headers: {
            Accept: "*",
            "content-type": "multipart/form-data; boundary=----WebKitFormBoundaryfqGXNd6fTPHYICAT"
          },
          data: formdata,
        })
        .then((res) => {
          if (res.tx_status === "00") {
            this.uploadImgUrl = res.pic_url;
            // this.$emit("input", this.uploadImgUrl);
            this.$emit("change", this.uploadImgUrl);
          }
        });
    },
    changeInput(e) {
      if (e) {
        this.uploadImgUrl = e;
      } else {
        this.$refs.files.value = "";
        this.uploadImgUrl = "";
      }
      this.$emit("input", this.uploadImgUrl);
      this.$emit("change", this.uploadImgUrl);
    },
  },
};
</script>
<style lang="less" scoped>
.file {
  position: absolute;
  width: 100%;
  padding: 100%;
  right: 0;
  top: 0;
  opacity: 0;
}
/deep/.el-input-group__append,
/deep/.el-input-group__prepend {
  padding: 0 10px !important;
  overflow: hidden;
}
.iconfont {
  font-size: 12px;
}
.uploadimg {
  width: 100px;
  height: 100px;
  margin-top: 20px;
}
</style>
